﻿using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Web;
using System.Web.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.IdentityModel;
using System.Configuration;
using System.Web.ApplicationServices;
using Microsoft.IdentityModel.Web;
using ContosoProviders;

namespace CustomMemberShipProviderWP.LoginCustom
{
    [ToolboxItemAttribute(false)]
    public partial class LoginCustom : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public LoginCustom()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            txtUsername.Focus();
            SPWeb web = SPContext.Current.Web;
            if (web.CurrentUser != null)
            {
                LoginBox.Visible = false;
                lbError.Text = "I'm Logged in now what!";
                btnLogout.Visible = true;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                 BaseMember provider = new BaseMember();
                bool validateStatus = provider.ValidateUser(txtUsername.Text, txtPassword.Text);

                if (validateStatus)
                {
                    lbError.Text = "";
                    bool status = SPClaimsUtility.AuthenticateFormsUser(
                            Context.Request.UrlReferrer,
                            txtUsername.Text,
                            txtPassword.Text);

                    if (status)
                    {
                        HttpContext.Current.Response.Redirect("/Pages/default.aspx");
                    }

                    
                }
                else
                { lbError.Text = "GO Away :( you are not a part of this site."; }
            }
            catch (Exception ex)
            {
                lbError.Text = ex.Message;
            }
        }
        public static void GetLoggedUser()
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {

                }
            }

        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            SPSite Site = SPContext.Current.Site;
            FormsAuthentication.SignOut();

            var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            // Clear .ASPAUTH cookie key.
            if (authCookie != null)
            {
                var myCookie = new HttpCookie(authCookie.Name) { Expires = DateTime.Now.AddDays(-1) };
                HttpContext.Current.Response.Cookies.Add(myCookie);
            }

            SPIisSettings iisSettingsWithFallback = Site.WebApplication.GetIisSettingsWithFallback(Site.Zone);
            if (iisSettingsWithFallback.UseClaimsAuthentication)
            {
                FederatedAuthentication.SessionAuthenticationModule.SignOut();
                // Clear FedAuth Cookie key
                FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
            }


            HttpContext.Current.Response.Redirect("/Pages/default.aspx");
        }
    }
}
